package com.xcw.bb.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import com.xcw.bb.entity.User;
import com.xcw.bb.service.UserService;
import com.xcw.bb.serviceImpl.UserServiceImpl;

/**
 * Servlet implementation class Login
 */
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAction() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		this.doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取表单中的值
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		try {
			//调用service方法
			UserService userService=new UserServiceImpl();
			
			User user=userService.queryUserByUserNameAndPassword(username, password);
			
			if(user==null){
				response.sendRedirect(request.getContextPath()+"/index.html");
			}else{
				//将用户的realname保存在session作用域中
				HttpSession session=request.getSession(true);
				session.setAttribute("user", user);
				session.setAttribute("login", "login");
				String role=user.getRole();
				//判断是教师还是学生
				if("student".equals(role)){
					response.sendRedirect(request.getContextPath()+"/student/queryAll");
					System.out.println("学生登录");
				}
				if("teacher".equals(role)){
					response.sendRedirect(request.getContextPath()+"/teacher/queryInteract.jsp");
					System.out.println("教师登录");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
